<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Service\EncryptService;
use Hyperf\Utils\Context;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;


class EncryptionMiddleware implements MiddlewareInterface
{

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var Response
     */
    private $response;

    /**
     * @var EncryptService
     */
    private $cryptService;

    public function __construct(ContainerInterface $container, Response $response, EncryptService $cryptService)
    {
        $this->container = $container;
        $this->response = $response;
        $this->cryptService = $cryptService;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $json = '';
        if($request->getMethod() === 'GET'){
            $queryData = $request->getQueryParams();
            $json = $queryData['query'] ?? '';
        }
        if($request->getMethod() === 'POST'){
            $params = $request->getParsedBody();
            $json = $params['json'] ?? '';
        }
        try {
            if(!$json){
                Context::set('params',[]);
                return $handler->handle($request);
            }
            // 解密
            $t = explode('##', $json);
            $resStr = '';
            foreach($t as $item) {
                if(!$item) {
                    continue;
                }
                var_dump($item);
                var_dump($this->cryptService->RSADecrypt($item));
                $resStr .= $this->cryptService->RSADecrypt($item);
            }
            $resStr = trim($resStr, '"');
            // 数据添加到上下文
            Context::set('params', json_decode($resStr, true));
        }catch (\JsonException $e) {
            return $this->response->json(
                \App\Common\Response::fail('http param error','004',[$e->getMessage()])
            );
        }
        return $handler->handle($request);
    }


}
